import 'package:airbnb_clone/constant/constant.dart';
import 'package:airbnb_clone/internal/http/dao/article_comment_create_dao.dart';
import 'package:airbnb_clone/internal/http/dao/article_comment_view_dao.dart';
import 'package:airbnb_clone/internal/http/dao/article_detail_dao.dart';
import 'package:airbnb_clone/internal/http/dao/friend_user_dao.dart';
import 'package:airbnb_clone/models/article.dart';
import 'package:airbnb_clone/models/article_comment.dart';
import 'package:flutter/material.dart';

import '../../components/dialog/login_check_dialog.dart';
import '../../components/dialog/msg_dialog.dart';
import '../../internal/login_check/login_check.dart';
import '../../models/response.dart';

// ignore: must_be_immutable
class ArticleDetailPage extends StatefulWidget {
  int articleId;
  ArticleDetailPage({required this.articleId, super.key});

  @override
  State<ArticleDetailPage> createState() => _ArticleDetailPageState();
}

class _ArticleDetailPageState extends State<ArticleDetailPage> {
  final String _belongName = "FlutterTopic";
  bool _isFavorite = false;
  Article _article = Article(
      id: 0,
      author: "加载失败",
      authorId: 0,
      title: "加载失败",
      context: "加载失败",
      view: 0,
      belong: "加载失败",
      belongIconUrl: "加载失败",
      createTime: DateTime(0, 0, 0),
      imgUrls: ["加载失败"]);
  final List<ArticleComment> _commentList = [];
  String username = "";
  String userImg = "https://t.mwm.moe/pc/";
  final TextEditingController _inputCommentController = TextEditingController();
  String _commentField = "";
  @override
  void initState() {
    super.initState();
    _loadArticleData();
    _loadArticleCommentData();
  }

  // 关注用户
  Future<void> _friendUser(int friendId) async {
    TiebaResponse response = await FriendUserDao.friend(friendId);

    if (response.code == 200) {
      // ignore: use_build_context_synchronously
      MsgDialog.msgDialog(context, response.msg);
    } else {
      // ignore: use_build_context_synchronously
      MsgDialog.msgDialog(context, response.msg);
    }
  }

  // 加载文章内容
  Future<void> _loadArticleData() async {
    TiebaResponse response = await ArticleDeatilDao.get(widget.articleId);
    if (response.code == 200) {
      setState(() {
        username = response.result["user_name"];
        _article = Article(
            id: response.result["id"],
            author: response.result["user_name"],
            authorId: response.result["user_id"],
            title: response.result["title"],
            context: response.result["article_context"],
            view: response.result["like"],
            belong: response.result["belong"],
            belongIconUrl: "https://t.mwm.moe/pc/",
            createTime: DateTime.parse(response.result["create_time"]),
            imgUrls: [response.result["img_url"]]);
      });
    } else {
      // ignore: use_build_context_synchronously
      MsgDialog.msgDialog(context, response.msg);
    }
  }

  // 加载文章评论
  Future<void> _loadArticleCommentData() async {
    TiebaResponse response = await ArticleCommentViewDao.get(widget.articleId);
    if (response.code == 200) {
      setState(() {
        _commentList.clear();
        for (var comment in response.result["list"]) {
          _commentList.add(ArticleComment(
              id: comment["id"],
              userId: comment["user_id"],
              liked: 0,
              userName: comment["user_name"],
              userImg: userImg,
              context: comment["context"],
              createTime: DateTime.parse(comment["create_time"])));
        }
        // _commentList.add(ArticleComment(id: id, userId: userId, liked: liked, userName: userName, userImg: userImg, context: context, createTime: createTime))
      });
    } else {
      // ignore: use_build_context_synchronously
      MsgDialog.msgDialog(context, response.msg);
    }
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.sizeOf(context);
    return Material(
      child: Scaffold(
        body: Container(
          height: size.height,
          decoration:
              BoxDecoration(gradient: LinearGradient(colors: bgGradientColor)),
          child: SingleChildScrollView(
              child: Column(
            children: [
              SizedBox(
                height: size.height * 0.1,
                child: buildTopBar(context, _belongName),
              ),
              SizedBox(
                height: size.height * 0.79,
                child: buildArticleBody(context),
              ),
              Container(
                // 由输入框决定
                // height: size.height * 0.17,
                color: Colors.white,
                child: buildCommentTextField(context),
              )
            ],
          )),
        ),
      ),
    );
  }

// 顶部
  Widget buildTopBar(BuildContext context, String belongName) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8),
      decoration:
          BoxDecoration(gradient: LinearGradient(colors: topBarBgColor)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          IconButton(
            icon: const Icon(Icons.arrow_back),
            onPressed: () {
              // context.pop();
              Navigator.of(context).pop(false);
            },
          ),
          Text(
            belongName,
            style: TextStyle(
                decorationColor: Colors.white.withOpacity(0),
                textBaseline: TextBaseline.alphabetic,
                color: Colors.black,
                fontSize: 24,
                fontWeight: FontWeight.w500),
          ),
          const Icon(Icons.ios_share_sharp)
        ],
      ),
    );
  }

// 中间
  Widget buildInfoCard(BuildContext context, Article article) {
    return Container(
      margin: const EdgeInsets.only(top: 14),
      padding: const EdgeInsets.all(8),
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 作者头像等
          SizedBox(
            height: 100,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  width: 100,
                  height: 100,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(8),
                    child: Image.network(
                      article.belongIconUrl,
                      fit: BoxFit.cover,
                      errorBuilder: (context, error, stackTrace) {
                        return Image.asset("assets/images/netError.jpg");
                      },
                    ),
                  ),
                ),
                const SizedBox(
                  width: 10,
                ),
                // 作者，标题，创建时间
                SizedBox(
                  width: 200,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        article.author,
                        style: titleTextStyle,
                        maxLines: 1,
                      ),
                      Text(
                        article.title,
                        style: titleTextStyle,
                        maxLines: 1,
                      ),
                      Text(
                        "${article.createTime}",
                        style: authorTextStyle,
                      ),
                    ],
                  ),
                ),
                // 关注按钮
                Expanded(
                    child: TextButton(
                  style: ButtonStyle(
                      shape: MaterialStateProperty.all(RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8))),
                      overlayColor: MaterialStateProperty.resolveWith((states) {
                        return const Color.fromARGB(120, 124, 120, 120);
                      })),
                  child: Text(
                    "关注",
                    style: titleTextStyle,
                  ),
                  onPressed: () {
                    _friendUser(article.authorId);
                  },
                ))
              ],
            ),
          ),
          // 文章内容
          Container(
            padding: const EdgeInsets.all(8),
            height: 300,
            width: MediaQuery.sizeOf(context).width,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  " ${article.title}",
                  style: titleTextStyle,
                ),
                Text(
                  " ${article.context}",
                  style: contextTextStyle,
                )
              ],
            ),
          ),
          // 底部小组件
          Expanded(
              child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              GestureDetector(
                onTap: () {
                  setState(() {
                    _isFavorite = !_isFavorite;
                  });
                },
                child: Row(
                  children: [
                    Icon(_isFavorite ? Icons.favorite : Icons.favorite_border),
                    Text(
                      "点赞",
                      style: normalTextStyle,
                    ),
                    Text(
                      "(滑至底部查看评论)",
                      style: normalTextStyle,
                    )
                  ],
                ),
              )
            ],
          ))
        ],
      ),
    );
  }

// 评论列表
  Widget buildCommentList(
      BuildContext context, List<ArticleComment> commentList) {
    return Container(
        margin: const EdgeInsets.only(top: 14),
        color: Colors.white,
        padding: const EdgeInsets.symmetric(horizontal: 8),
        child: ListView.builder(
            padding: EdgeInsets.zero,
            itemCount: commentList.length,
            itemBuilder: (context, index) {
              String belongText = "关注";
              return Container(
                margin: const EdgeInsets.only(top: 10),
                height: 100,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 头像
                    Container(
                      padding: const EdgeInsets.all(10),
                      height: 75,
                      width: 75,
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(8),
                        child: Image.network(
                          commentList[index].userImg,
                          errorBuilder: (context, error, stackTrace) {
                            return Image.asset("assets/images/netError.jpg");
                          },
                        ),
                      ),
                    ),
                    const SizedBox(
                      width: 10,
                    ),
                    // 用户名 评论
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            commentList[index].userName == ""
                                ? "未设置名称"
                                : commentList[index].userName,
                            style: titleTextStyle,
                          ),
                          Text(
                            " ${commentList[index].context}",
                            maxLines: 3,
                            overflow: TextOverflow.ellipsis,
                            style: normalTextStyle,
                          ),
                        ],
                      ),
                    ),
                    Column(
                      children: [
                        TextButton(
                          style: ButtonStyle(
                              shape: MaterialStateProperty.all(
                                  RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(8))),
                              overlayColor:
                                  MaterialStateProperty.resolveWith((states) {
                                return const Color.fromARGB(120, 124, 120, 120);
                              })),
                          child: Text(
                            belongText,
                            style: normalTextStyle,
                          ),
                          onPressed: () {
                            _friendUser(commentList[index].userId);
                          },
                        ),
                        TextButton(
                          style: ButtonStyle(
                              shape: MaterialStateProperty.all(
                                  RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(8))),
                              overlayColor:
                                  MaterialStateProperty.resolveWith((states) {
                                return const Color.fromARGB(120, 124, 120, 120);
                              })),
                          child: Text(
                            "点赞",
                            style: normalTextStyle,
                          ),
                          onPressed: () {},
                        ),
                      ],
                    )
                  ],
                ),
              );
            }));
  }

// 文章主题
  Widget buildArticleBody(BuildContext context) {
    final size = MediaQuery.sizeOf(context);
    return ListView(
      padding: EdgeInsets.zero,
      children: [
        SizedBox(
          height: size.height * 0.6,
          child: buildInfoCard(context, _article),
        ),
        SizedBox(
          height: size.height * 0.7,
          child: buildCommentList(context, _commentList),
        ),
      ],
    );
  }

// 评论组件
  Widget buildCommentTextField(BuildContext context) {
    final size = MediaQuery.sizeOf(context);
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Expanded(child: Container()),
        Container(
          padding: const EdgeInsets.all(14),
          width: size.width * 0.8,
          constraints: BoxConstraints(
              minHeight: size.height * 0.1, maxHeight: size.height * 0.4),
          child: TextField(
            controller: _inputCommentController,
            maxLines: null,
            maxLength: 200,
            decoration: InputDecoration(
                filled: true,
                fillColor: Colors.grey[200],
                border: OutlineInputBorder(
                  borderSide: BorderSide.none,
                  borderRadius: BorderRadius.circular(7),
                ),
                hintText: '友善之言，心底生馨',
                // helperText: "",
                counterText: ''),
            onTap: () {},
          ),
        ),
        TextButton(
            style: ButtonStyle(
                shape: MaterialStateProperty.all(RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8))),
                overlayColor: MaterialStateProperty.resolveWith((states) {
                  return const Color.fromARGB(120, 124, 120, 120);
                })),
            onPressed: () {
              FocusScope.of(context).unfocus();
              setState(() {
                _commentField = _inputCommentController.text;
                addComment();
              });

              _inputCommentController.clear();
            },
            child: const Text(
              "发送",
              style: TextStyle(color: Colors.black),
            ))
      ],
    );
  }

//  发送消息
  Future<void> addComment() async {
    if (!LoginCheck.check()) {
      LoginCheckDialog.loginDialog(context);
      return;
    }
    TiebaResponse response =
        await ArticleCommentCreateDao.create(widget.articleId, _commentField);
    if (response.code == 200) {
      // ignore: use_build_context_synchronously
      MsgDialog.msgDialog(context, response.msg);
      _loadArticleCommentData();
    } else {
      // ignore: use_build_context_synchronously
      MsgDialog.msgDialog(context, response.msg);
    }
  }
}
